<template>
  <div class="creator-editor__container">
    <!-- 顶部选项卡 -->
    <div class="creator-editor-header">
      <div class="hb-cpt__pagination hb-cpt__slide-tab line">
        <div class="hb-cpt__pagination-outer">
          <div class="hb-cpt__pagination-inner">
            <button class="slide-tab__tab-item active">
              <div class="slide-tab__tab-label">发布</div>
            </button>
            <div class="slide-tab-tab__bar"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图文编辑区域 -->
    <div class="hb-page-creator__editor-image-text">
      <div class="editor-image-text__section">
        <!-- 编辑内容 -->
        <div class="editor-image-text__main-content">
          <!-- 标题 -->
          <div class="hb-cpt__editor-title editor-image-text__title">
            <div class="editor-title__container">
              <div
                class="ProseMirror hb-editor"
                contenteditable="true"
                :data-placeholder="'填写标题'"
                ref="titleRef"
                @input="onTitleInput"
              ></div>
            </div>
            <div class="editor-title__cnt-indicator">{{ titleLength }}/30</div>
          </div>

          <!-- 正文 -->
          <div class="image-text__edit-content">
            <div class="image-text__edit-content--inner">
              <WangEditor v-model="content" ref="wangEditorRef" />
            </div>
          </div>
        </div>

        <!-- 关联模块 -->
        <div class="editor__more-info topics">
          <div class="editor__more-info--left">
            <!-- 将标题和已选话题合并到同一容器 -->
            <div class="topic-header-container">
              <div class="editor__more-info-title">关联话题</div>
              <div class="selected-topics">
                <div
                  v-for="(topic, index) in topics"
                  :key="index"
                  class="selected-topic-item"
                >
                  #{{ topic.topicName }}
                  <span class="remove-topic" @click.stop="removeTopic(index)"
                    >×</span
                  >
                </div>
              </div>
            </div>
            <div class="editor__more-info-desc">{{ topics.length }}/2</div>
          </div>
          <div class="editor__more-info--right">
            <button
              v-if="topics.length < 2"
              class="add-community-btn"
              @click="showModal = true"
            >
              添加话题
            </button>
          </div>
        </div>
        <CommunityTopic
          v-if="showModal"
          :selected-topics="topics"
          @close="showModal = false"
          @add-topic="addTopicToList"
        />
      </div>
    </div>

    <!-- 底部操作区 -->
    <div class="creator-editor__footer">
      <button class="publish-btn" @click="handlePublish">
        {{ isEditing ? '修改' : '立即发布' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import CommunityTopic from './CommunityTopic.vue'
import { uploadAvatarFile } from '@/apis/file.js'
import WangEditor from './components/RichTextEditor.vue'
import { createArticle, getArticleDetail, updateArticle } from '@/apis/article'

import { useRouter, useRoute } from 'vue-router'

const topics = ref([])
const showModal = ref(false)

const title = ref('')
const content = ref('')

const titleRef = ref(null)
const contentRef = ref(null)

const isPreviewing = ref(false)

const titleLength = computed(() => title.value.replace(/<[^>]+>/g, '').length)

const onTitleInput = () => {
  title.value = titleRef.value.innerHTML
}

const onContentInput = () => {
  content.value = contentRef.value.innerHTML
}

const router = useRouter() // 获取路由实例
// 新增内容空判断方法
const isContentEmpty = (html) => {
  // 创建临时容器解析内容
  const container = document.createElement('div')
  container.innerHTML = html

  // 检查是否存在有效内容
  const hasText = container.textContent.trim() !== ''
  const hasImage = container.querySelector('img') !== null

  return !hasText && !hasImage
}
const handlePublish = async () => {
  const html = content.value
  const articleTitle = title.value.replace(/<[^>]+>/g, '').trim()

  if (!articleTitle) {
    ElMessage.warning('标题不能为空')
    return
  }

  // 内容验证（新增）
  if (isContentEmpty(html)) {
    ElMessage.warning('内容不能为空')
    return
  }
  // 新增话题数量验证
  if (topics.value.length === 0) {
    ElMessage.warning('请选择至少一个关联话题')
    return
  }

  // 提取内容列表
  const container = document.createElement('div')
  container.innerHTML = html

  const contents = []
  let order = 0
  for (const child of container.childNodes) {
    const img = child.querySelector?.('img')
    if (img) {
      contents.push({
        contentType: 2,
        imageUrl: img.src,
        orderIndex: order++,
      })
    } else if (child.textContent.trim()) {
      contents.push({
        contentType: 1,
        textContent: child.textContent.trim(),
        orderIndex: order++,
      })
    }
  }

  const topicIds = topics.value.map((topic) => topic.topicId)

  const postData = {
    title: articleTitle,
    contents,
    cover: contents.find((c) => c.contentType === 2)?.imageUrl || '',
    topicIds: topicIds,
  }

  try {
    if (isEditing.value) {
      console.log('修改', postData)
      // ✅ 修改文章逻辑
      const res = await updateArticle(articleId.value, postData)
      if (res.code === '200') {
        ElMessage.success('修改成功')
        router.push(`/home/article/${articleId.value}`)
      } else {
        ElMessage.error(res.message || '修改失败')
      }
    } else {
      console.log('新建', postData)
      // ✅ 新建文章逻辑
      const res = await createArticle(postData)
      if (res.code === '200') {
        ElMessage.success('发布成功')
        router.push('/home/article') // 或者跳转到新文章页
      } else {
        ElMessage.error(res.message || '发布失败')
      }
    }
  } catch (err) {
    ElMessage.error('请求失败')
    console.error('操作失败:', err)
  }
}

// 键盘事件监听（仅保留ESC关闭）
document.addEventListener('keydown', (e) => {
  if (e.key === 'Escape' && isPreviewing.value) {
    closePreview()
  }
})

// 修改添加话题方法
const addTopicToList = (topic) => {
  // 双重校验确保不超过上限
  if (topics.value.length >= 2) return
  // 防止重复添加
  if (!topics.value.some((t) => t.topicId === topic.topicId)) {
    topics.value.push(topic)
  }
}

const removeTopic = (index) => {
  topics.value.splice(index, 1)
}

const route = useRoute()
const articleId = ref(route.params.id || null)
const isEditing = computed(() => !!articleId.value)

// 新增编辑器引用
const wangEditorRef = ref(null)

// 修改初始化逻辑
onMounted(async () => {
  if (!isEditing.value) return

  try {
    const res = await getArticleDetail(articleId.value)
    const data = res.data

    // 设置标题
    title.value = data.title
    titleRef.value.innerHTML = data.title

    // 等待编辑器组件初始化完成
    await nextTick()

    // 转换并设置内容
    const htmlContent = contentListToHtml(data.contentList)
    wangEditorRef.value?.setHtml(htmlContent)
  } catch (err) {
    console.error('加载文章详情失败:', err)
  }
})

function contentListToHtml(list) {
  return list
    .slice() // 避免原数组被改动
    .sort((a, b) => a.orderIndex - b.orderIndex)
    .map((item) => {
      if (item.contentType === 1 && item.textContent) {
        return `<p>${item.textContent}</p>`
      }
      if (item.contentType === 2 && item.imageUrl) {
        return `<p><img src="${item.imageUrl}" /></p>`
      }
      return ''
    })
    .join('')
}
</script>

<style scoped>
.creator-editor__container {
  max-width: 960px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.creator-editor-header {
  margin-bottom: 20px;
}

.hb-cpt__slide-tab {
  display: flex;
  justify-content: space-between;
}

.hb-cpt__pagination-inner {
  display: flex;
  gap: 16px;
  position: relative;
}

.slide-tab__tab-item {
  padding: 10px 18px;
  font-size: 16px;
  background: none;
  border: none;
  cursor: pointer;
  color: #999;
}

.slide-tab__tab-item.active {
  color: #000;
  font-weight: 600;
  border-bottom: 2px solid #007bff;
}

.editor-title__container .ProseMirror {
  min-height: 40px;
  font-size: 16px;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.image-text__edit-content--inner .ProseMirror {
  min-height: 200px;
  font-size: 14px;
  line-height: 1.6;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
}

.editor-title__cnt-indicator {
  text-align: right;
  font-size: 12px;
  color: #888;
  margin-top: 4px;
}

.editor__more-info {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.publish-btn {
  margin-top: 24px;
  background: #000;
  color: #fff;
  padding: 12px 32px;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  float: right;
  cursor: pointer;
}

.ProseMirror:empty::before {
  content: attr(data-placeholder);
  color: #aaa;
  font-size: 14px;
}

.add-community-btn {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  flex-shrink: 0;
}

.add-community-btn:hover {
  background-color: #0056b3;
}

.selected-topic-item {
  background: #f0f2f5;
  padding: 4px 8px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.remove-topic {
  cursor: pointer;
  color: #666;
  font-weight: bold;
  padding-left: 4px;
}

.remove-topic:hover {
  color: #ff4d4f;
}

.topic-header-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.editor__more-info--left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selected-topics {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin: 0;
}

.editor__more-info-title {
  white-space: nowrap;
}
</style>
